package com.example.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.server.mapper.RoleMapper;
import com.example.common.pojo.Admin;
import com.example.server.mapper.AdminMapper;
import com.example.common.pojo.Role;
import com.example.server.security.context.SecurityContextHolder;
import com.example.server.security.context.TokenBasedSecurityContextHolder;
import com.example.server.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.vo.RespBean;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小红
 * @since 2022-09-02
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private SecurityContextHolder securityContextHolder;

    @Override
    public RespBean login(Admin admin, HttpSession session) {

        String captcha = (String) session.getAttribute("captcha");

        if (StringUtils.isEmpty(admin.getCode()) || !admin.getCode().equalsIgnoreCase(captcha)) {
            return RespBean.error(403,"验证码不正确！");
        }

        Admin adminFromDb = adminMapper.selectOne(new QueryWrapper<Admin>()
                .eq("username", admin.getUsername()));

        if (adminFromDb != null) {
            if (BCrypt.checkpw(admin.getPassword(), adminFromDb.getPassword())) {
                System.out.println(admin.getPassword());
                // 同步用户对应的角色列表
                List<Role> roles = roleMapper.findByAdminId(adminFromDb.getId());
                adminFromDb.setRoles(roles);
                securityContextHolder.setUserDetails(adminFromDb);
                if (securityContextHolder instanceof TokenBasedSecurityContextHolder) {

                    String token = Jwts.builder()
                            .setSubject(adminFromDb.getUsername())
                            .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))
                            .signWith(SignatureAlgorithm.HS256, "test")
                            .compact();
                    Map<String, String> params = new HashMap<>();
                    params.put("tokenHead","Bearer");
                    params.put("token",token);

                    return RespBean.success(params);
                }
                return RespBean.success();
            }
        }

        throw RespBean.AUTH_FAILED_ERROR_402.toException();
    }

    @Override
    public List<Admin> getAdmin() {
        return adminMapper.getAdmin();
    }

    @Override
    public List<Admin> getAdminsByKeywords(String keywords) {
        /**
         * 根据关键词模糊查询
         *携带roles列表
         * 不能查看自己数据
         */
        Admin userDetails = (Admin) securityContextHolder.getUserDetails();
        return adminMapper.findAdminByKeywords(keywords, userDetails.getId());
    }

    @Override
    public void deleteAdmin(Integer id) {
        adminMapper.deleteAdminById(id);
    }
}
